//
//  UITextFieldUtils.swift
//
//  Created by Ink on 2024/12/12.
//  Copyright © 2024 ZM. All rights reserved.
//

import Foundation

extension UITextField {
    
    fileprivate struct AssociatedKeys {
        static var zmMaxLength = "zmMaxLength"
    }
    
    var zmMaxLength: Int {
        set { mUtilMap[AssociatedKeys.zmMaxLength] = newValue }
        get { mUtilMap[AssociatedKeys.zmMaxLength] as? Int ?? 0 }
    }
        
    func textViewDidChangeMaxLengthHandler() {
        
        guard let text = text else { return }
        
        var cutOut = false
        
        let lang = textInputMode?.primaryLanguage
        if lang == "zh-Hans" || lang == "zh-Hant" {
            if let selectedRange = markedTextRange {
                //非高亮（高亮表示只显示了汉字的拼音字母，汉字还未输入进去的状态）
                cutOut = position(from: selectedRange.start, offset: 0) == nil
            }
        }
        else {
            cutOut = true
        }
        
        if cutOut == true,
           text.length > zmMaxLength{
            self.text = text.substring(toIndex: zmMaxLength)
        }
    }
    
    func checkShouldChange(text: String?) -> (shouldChange:Bool, text: String?) {
        
        guard let text = text, self.zmMaxLength > 0 else { return (true, text) }
        
        var shouldChange = true
        var substring = text
        
        let lang = textInputMode?.primaryLanguage
        if lang == "zh-Hans" || lang == "zh-Hant" {
            if let selectedRange = markedTextRange {
                //非高亮（高亮表示只显示了汉字的拼音字母，汉字还未输入进去的状态）
                let position = position(from: selectedRange.start, offset: 0)
                if position == nil, self.zmMaxLength > 0 {
                    shouldChange = text.length <= self.zmMaxLength
                }
            }
        }
        else {
            shouldChange = text.length <= self.zmMaxLength
        }
        
        if shouldChange == true {
           substring = text.substring(toIndex: self.zmMaxLength)
        }
        
        return (shouldChange, substring)
        
    }
}
